package org.yuanqiframework.yuanqi.web.auth.service;

import org.springframework.stereotype.Component;
import org.yuanqiframework.yuanqi.web.auth.entity.LoginDTO;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Set;

@Component
public class LoginService {
    @Resource
    private TokenService tokenService;

    /**
     * 判断密码是否匹配
     */
    public boolean passwordMatch(String dbPassword, String userPassword) {
        if (dbPassword == null || userPassword == null) {
            return false;
        }
        if (dbPassword.equals(userPassword)) {
            return true;
        }
        return false;
    }

    /**
     * 登录获取token
     *
     * @param userId   用户唯一标识
     * @param username 用户中文
     * @param roles
     * @return
     */
    public String loginGetToken(String userId, String username, Set<String> roles, Map<String, Object> infoMap) {
        //缓存角色信息到redis，并创建token
        LoginDTO e = new LoginDTO();
        e.setUserId(userId);
        e.setUsername(username);
        e.setRoles(roles);
        if (infoMap != null) {
            e.setInfoMap(infoMap);
        }
        return tokenService.createToken(e);
    }

    public String loginGetToken(String userId, String username, Set<String> roles) {
        return loginGetToken(userId, username, roles, null);
    }

    public boolean logout(HttpServletRequest request) {
        tokenService.delLoginDTO(request);
        return true;
    }
}
